'use strict';

var app = angular.module("myApp", []);
app.controller('configController', ['$scope', '$compile', '$sce', function ($scope, $compile) {
    $scope.category = [{ title: '故障模块', name: "module" }, { title: '故障分组', name: "group" }];

    $scope.items = [];
    $scope.type = null;

    $scope.loadConfigure = function () {
        getConfigure($scope.type.name, function (data) {
            $scope.items = data.map(function (x) {
                if (x.indexOf(':') < 0) {
                    return {
                        category: '',
                        name: x,
                        $onEdited: false
                    };
                }
                var arr = x.split(':', 2);
                return {
                    category: arr[0],
                    name: arr[1],
                    $onEdited: false
                };
            });
            $scope.$apply();
        });
    };

    $scope.appendItem = function () {
        $scope.items.push({
            name: '新条目',
            $onEdited: true
        });
    };

    $scope.saveConfigure = function () {
        var session = neo4jService.getSession();
        var data = $scope.items.map(function (x) {
            return x.category + ':' + x.name;
        });
        var resultPromise = session.run('merge (a:Configure{ ftype:"' + $scope.type.name + '"})\n         ON CREATE set a.data={jsonStr} ON MATCH set a.data={jsonStr}', { jsonStr: JSON.stringify(data) });
        resultPromise.then(function (result) {
            session.close();
            console.info("更新成功。");
            $scope.items.forEach(function (x) {
                return x.$onEdited = false;
            });
            $scope.$apply();
        });
    };

    $scope.persistItem = $scope.saveConfigure;

    $scope.modifyItem = function (item) {
        item.$onEdited = true;
    };

    $scope.deleteItem = function (index) {
        $scope.items.splice(index, 1);
        $scope.saveConfigure();
    };
}]);
